
/*
 * Copyright 2016 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
 *
 * This software is published under the terms of the YONYOU Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 *
 * @Project Name : marketing-wechat-open-api
 *
 * @File name : MaintainController.java
 *
 * @Author : Wang HuiCheng
 *
 * @Date : 2016年11月3日
 *
 ----------------------------------------------------------------------------------
 *     Date             Who              Version     Comments
 * 1.  2016年11月3日    Wang HuiCheng    1.0
 *
 *
 *
 *
 ----------------------------------------------------------------------------------
 */
	
package com.yonyou.gmcc.gateway.wechat.controller.maintain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.marketing.common.dto.maintain.AdviserDto;
import org.marketing.common.dto.maintain.CarModelDto;
import org.marketing.common.dto.maintain.InsuranceDto;
import org.marketing.common.dto.maintain.MaintainDealerDto;
import org.marketing.common.dto.maintain.MaintainDto;
import org.marketing.common.dto.maintain.SosHelpDealerInfoDto;
import org.marketing.common.dto.maintain.SosHelpDto;
import org.marketing.common.dto.maintenanceorder.MaintenanceDto;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.gmcc.gateway.wechat.common.ApiVersionConsts;
import com.yonyou.gmcc.gateway.wechat.common.HttpClientUtil;
import com.yonyou.gmcc.gateway.wechat.controller.BaseController;
import com.yonyou.gmcc.gateway.wechat.service.interfaces.MaintainServiceInterFace;

/**
 * 售后杨修预约和一键救援CONTROLLER
 * @author Wang HuiCheng
 * @date 2016年11月3日
 */
@RestController
@RequestMapping(value = ApiVersionConsts.BASE_PATH+"/maintain" )
public class MaintainController extends BaseController{
    
    private Logger logger = Logger.getLogger(MaintainController.class);
    
    @Value("${dealerApp.url:https://carapptest.gtmc.com.cn/appservice}")
    public String dealerAppUrl;
    
    public  final  String sosDealerUrl = "/okr/oneKeyResuce/resuceSearch.json"; 
    
    @Autowired
    private MaintainServiceInterFace maintainServiceInterFace;
    
    /**
    *根据微信账号ID查找该微信用户下锁绑定的车辆信息
    * @author WangHuicheng
    * 
    * @date 2016年11月2日
    * @param brandCode
    * @return
    */
    @RequestMapping(value = { "/getBindCarInfos" }, method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<CarModelDto> getCarInfoByOpenID(HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<CarModelDto> dtoList = null;
        this.logger.info(this.getClass().getName()+"getCarInfoByOpenID:begin");
        try{
            //String openId = "omLPIwAROJROvIo06uHBOp52atNQ";
            String openId = this.getOpenId(request);
            this.logger.info("openId:"+openId);
            dtoList =  maintainServiceInterFace.getBindCarInfos(openId);
            if(CheckUtil.NullOrEmpty(dtoList)){
                dtoList = new ArrayList<>();
            }
        }catch (Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return dtoList;
    }
    
    /**
     * 
    * 保存养修预约信息
    * @author WangHuicheng
    * @date 2016年11月4日
    * @return 成功信息
     */
    @RequestMapping(value={"/saveMaintain"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String,Object> saveMaintain(@RequestBody MaintainDto maintainDto,HttpServletRequest request, HttpServletResponse response)throws Exception{
        this.logger.info(this.getClass().getName()+":saveMaintain BEGIN:");
        Map<String,Object> map = null;
        try{
           //String openId = "omLPIwAROJROvIo06uHBOp52atNQ";
           String openId = this.getOpenId(request);
            String authorizerAppid = this.getAuthorizerAppid(request);
            if(!CheckUtil.NullOrEmpty(authorizerAppid)){
                maintainDto.setAuthorizerAppid(authorizerAppid);
            }
//            if (openId == null) {
//                openId = "oQWbqwLt1kF1XeDmFvziFsErNnU8";
//            }
           // String dealerCode = this.getDealerCode(request);
            //String dealerCode = this.getDealerCode(request);
//            if (dealerCode == null) {
//                dealerCode = "00000";
//            }
            this.logger.info("openId:"+openId);
           // this.logger.info("dealerCode:"+dealerCode);
            maintainDto.setOpenId(openId);
           // maintainDto.setDealerCode(dealerCode);
            map = maintainServiceInterFace.saveMaintain(maintainDto);
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return map;
    }
    
    /**
    * 更新养修预约状态
    * @author QianKun
    * @date 2016年12月30日
    * @param maintainDto
    * @return
    * @throws Exception
    */
    @RequestMapping(value={"/updateMaintainStatus"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String,Object> updateMaintainAppointStatus(@RequestBody MaintainDto maintainDto)throws Exception{
        Map<String,Object> map = maintainServiceInterFace.updateMaintainAppointStatus(maintainDto);
        return map;
    }
    
    /**
    * 更新一键救援状态
    * @author QianKun
    * @date 2016年12月30日
    * @param sosHelpDto
    * @return
    * @throws Exception
    */
    @RequestMapping(value={"/updateSosHelpStatus"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String,Object> updateSosHelpStatus(@RequestBody SosHelpDto sosHelpDto)throws Exception{
        Map<String,Object> map = maintainServiceInterFace.updateSosHelpStatus(sosHelpDto);
        return map;
    }
    
    /**
     * 
    *
    * @author WangHuicheng
    * 根据经销商代码取得该经销商下所有的服务人员
    * @date 2016年11月8日
    * @return
     */
    @RequestMapping(value={"/getDealerAdvisers/{dealerCode}"},method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    @ResponseBody
    public List<AdviserDto> getDealerAdvisers(@PathVariable("dealerCode") String dealerCode){
        List<AdviserDto> list = this.maintainServiceInterFace.getDealerAdvisers(dealerCode);
        if (CheckUtil.NullOrEmpty(list)){
            list = new ArrayList<>();
        }
        return list;
    }
    

    /**
    *
    * 紧急救援-经销商管理
    * @author WangHuicheng
    * @date 2016年11月10日
    * @param lat
    * @param lng
    * @return
     */
    @RequestMapping(value={"/getSosDealers"},method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    @ResponseBody
    public String getSosDealers(@RequestParam("lat") String lat,@RequestParam("lng") String lng){
        String url = dealerAppUrl + sosDealerUrl;
        HashMap<String,Object> paramMap = new HashMap<>();
        paramMap.put("lat", lat);
        paramMap.put("lng", lng);
        
        String result  = HttpClientUtil.sendGetRequest(url, paramMap);
        return result;
    }
    
    /**
     * 查询紧急救援经销商
     * 
     * @author WangHuicheng
     * @date 2016年12月28日
     * @param userId 用户ID或者是OPENID
     * @param lat 经度
     * @param lng 维度
     * @return 查询的经销商信息
     */
    @RequestMapping(value = { "/sosHelpDealerList" }, method = RequestMethod.GET)
    @ResponseBody
    public List<SosHelpDealerInfoDto> getSosHelpDealerInfo(@RequestParam("lat") String lat,
                                                           @RequestParam("lng") String lng,
                                                           HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<SosHelpDealerInfoDto> list = null;
        try{
            String userId = this.getOpenId(request);
//          if (StringUtils.isEmpty(userId)){
//              userId = "omLPIwKyiL3pmPx5c3WPKgtNvpZc";
//          }
            list = this.maintainServiceInterFace.getSosHelpDealerInfo(userId, lat, lng);
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return list;
    }
    
    /**
     * 
    * 取得保险公司信息
    * @author WangHuicheng
    * @date 2016年11月11日
    * @return
     */
    @RequestMapping(value={"/getInsuranceList"},method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    @ResponseBody
    public List<InsuranceDto> getInsuranceList(){
        List<InsuranceDto> list = this.maintainServiceInterFace.getInsuranceList();
        if (CheckUtil.NullOrEmpty(list)){
            list = new ArrayList<>();
        }
        return list;
        
    }
    
    /**
     * 
    * 撒送SOS信息
    * @author WangHuicheng
    * @date 2016年11月11日
    * @return
     */
    @RequestMapping(value = { "/sendSos" }, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> sendSos(@RequestBody SosHelpDto sosHelpDto ,
                                       HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.logger.info(this.getClass().getName()+":sendSos:BEGIN");
        Map<String, Object> map = null;
        try{
            String openId = this.getOpenId(request);
            this.logger.info("Latitude:"+sosHelpDto.getLatitude());
            this.logger.info("Longitude:"+sosHelpDto.getLongitude());
            this.logger.info("dealerCode:"+sosHelpDto.getDealerCode());
/*          
            if (null == openId){
                openId="omLPIwAROJROvIo06uHBOp52atNQ";
            }
*/            this.logger.info("openId:"+openId);
            sosHelpDto.setCarOwnerUserId(openId);
            map = this.maintainServiceInterFace.sendSos(sosHelpDto);
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return map;

    }
    
        
    /**
    *
    * @author QianKun
    * 养修预约列表查询
    * @date 2016年11月17日
    * @param userId
    * @return
    */
    @RequestMapping(value = { "/repairs" },method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintainDto> getMaintainData(@RequestParam("userId") Long userId) {
        List<MaintainDto> dtoList = maintainServiceInterFace.getMaintainData(userId);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
        }
        return dtoList;
    }
    
    /**
    *
    * @author QianKun
    * 养修预约详情查询
    * @date 2016年11月17日
    * @param resnId
    * @return
    */
    @RequestMapping(value = { "/repairs/{id}" }, method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintainDto> getMaintainDataById(@PathVariable(value="id") Long resnId) {
        List<MaintainDto> dtoList = maintainServiceInterFace.getMaintainDataById(resnId);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
        }
        return dtoList;
    }
    
    /**
    *
    * @author QianKun
    * 一鍵救援列表查詢
    * @date 2016年11月18日
    * @return
    */
    @RequestMapping(value = { "/rescues" },method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<SosHelpDto> getSosHelpData(@RequestParam("carOwnerUserId") String carOwnerUserId) {
        List<SosHelpDto> dtoList = maintainServiceInterFace.getSosHelpData(carOwnerUserId);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
        }
        return dtoList;
    }
    
    /**
    *
    * @author QianKun
    * 一鍵救援详情查询
    * @date 2016年11月18日
    * @return
    */
    @RequestMapping(value = { "/rescues/{id}" }, method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<SosHelpDto> getSosHelpDataById(@PathVariable(value="id") String soshelpId) {
        List<SosHelpDto> dtoList = maintainServiceInterFace.getSosHelpDataById(soshelpId);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
        }
        return dtoList;
    }
    
    /**
     * 
    * 取得空余时间-不包含工位信息，分时段的。每半小时为一个时段
    * @author WangHuicheng
    * @date 2016年12月7日
    * @param dealerCode
    * @param appDay
    * @return
    * @throws Exception
     */
    @RequestMapping(value = "/simple",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<String> getFreeTimeNoWorkStation(@RequestParam("appDay") String appDay,
                                                 @RequestParam("bookingType") String bookingType,
                                                 HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<String> timeList = null;
        this.logger.info(this.getClass().getName()+":getFreeTimeNoWorkStation:BEGIN");
        try{
            //String dealerCode = "270001";
            String dealerCode = this.getDealerCode(request);
            this.logger.info("dealerCode:"+dealerCode);
            this.logger.info("appDay:"+appDay);
            this.logger.info("bookingType:"+bookingType);
        
            timeList = maintainServiceInterFace.getFreeTimeNoWorkStation(dealerCode, appDay,bookingType);
            if (CheckUtil.NullOrEmpty(timeList)) {
                timeList = new ArrayList<>();
            }
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return timeList;
        
    }
    
    /**
    * 养修预约经销商，车辆信息查询
    * @author QianKun
    * @date 2017年2月17日
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/maintainSel",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintainDto> getMaintainSel(HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<MaintainDto> dtoList = null;
        try{
            //String openId = "omLPIwAROJROvIo06uHBOp52atNQ";
            String openId = this.getOpenId(request);
            dtoList = maintainServiceInterFace.getMaintainSel(openId);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
            }
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return dtoList;
    }
    
    /**
    * 养修搜索经销商城市
    * @author QianKun
    * @date 2017年2月21日
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/maintainSelectCity",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintainDealerDto> getSelectCity(@RequestParam("regionName") String regionName) throws Exception{
        List<MaintainDealerDto> dtoList = null;
        try{
            dtoList = maintainServiceInterFace.getSelectCity(regionName);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
            }
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return dtoList;
    }   
    
    /**
    * 全部省/市查询
    * 90011001：省,90011002：市
    * @author QianKun
    * @date 2017年2月21日
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/maintainDealerMap",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintainDealerDto> getMaintainDealerMap(@RequestParam("regionType") String regionType) throws Exception{
        List<MaintainDealerDto> dtoList = null;
        try{
            dtoList = maintainServiceInterFace.getMaintainDealerMap(regionType);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
            }
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return dtoList;
    }
    
    /**
    * 根据省查市
    * @author QianKun
    * @date 2017年3月1日
    * @param parentCode
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/SelectCityMap",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintainDealerDto> getSelectCityMap(@RequestParam("parentCode") String parentCode) throws Exception{
        List<MaintainDealerDto> dtoList = null;
        try{
            dtoList = maintainServiceInterFace.getSelectCityMap(parentCode);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
            }
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return dtoList;
    }
    
    /**
    * 查询该城市下的经销商
    * @author QianKun
    * @date 2017年2月21日
    * @param tmAdministrationId
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/maintainDealer",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintainDealerDto> getMaintainDealer(@RequestParam("regionName") String regionName,HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<MaintainDealerDto> dtoList = null;
        try{ 
            //String dealerCode = "270001";
            String dealerCode = this.getDealerCode(request);
            dtoList = maintainServiceInterFace.getMaintainDealer(regionName,dealerCode);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
            }
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return dtoList;
    }
    
    /**
    * 搜索某经销商
    * @author QianKun
    * @date 2017年3月1日
    * @param regionCode
    * @param dealerName
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/searchDealer",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintainDealerDto> getSearchDealer(@RequestParam("regionName") String regionName,@RequestParam("dealerName") String dealerName) throws Exception{
        List<MaintainDealerDto> dtoList = null;
        try{ 
            dtoList = maintainServiceInterFace.getSearchDealer(regionName,dealerName);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
            }
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return dtoList;
    }
    /**
    * 维修履历列表查询
    * @author QianKun
    * @date 2017年3月7日
    * @param vin
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/getMaintenance",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<MaintenanceDto> getMaintenance(@RequestParam("vin") String vin) throws Exception{
        List<MaintenanceDto> dtoList = null;
        try{ 
            dtoList = maintainServiceInterFace.getMaintenance(vin);
        if (CheckUtil.NullOrEmpty(dtoList)) {
            dtoList = new ArrayList<>();
            }
        }catch(Exception e){
            this.logger.error(e.getMessage(),e);
            throw e;
        }
        return dtoList;
    }
}
